<?php

namespace app\system\service;

use app\common\Jwt;
use app\model\SystemUser;
use app\traits\ServiceTrait;
use app\traits\UserTrait;
use think\facade\Cache;
use think\helper\Arr;

class UserService
{
    use ServiceTrait;
    use UserTrait;

    /**
     * 黑名单token
     * @param $token
     * @return string
     */
    public static function generateBlackToken($token): string
    {
        return md5($token);
    }

    /**
     * 默认设置
     * @return mixed
     */
    public function getUserSetting()
    {
        return json_decode('{"mode":"light","tag":true,"menuCollapse":false,"menuWidth":220,"layout":"classic","skin":"mine","i18n":false,"language":"zh_CN","animation":"ma-slide-down","color":"#165DFF"}');
    }

    public function isSuperAdmin(): bool
    {
        return $this->getUid() == 1;
    }

    public function login($data): array
    {
        $user = SystemUser::where(['username' => $data['username']])->find();
        if (!$user) {
            return [false, '用户登录信息错误'];
        }
        if (!password_verify($data['password'], $user->password)) {
            return [false, '用户登录权限错误'];
        }
        return [true, Jwt::getUserToken($user->id, 'system')];
    }


    public function logout($token): array
    {
        try {
            $ttl = config("jwt.system.payload.expire") - time();
            Cache::set($token, 1, $ttl);
        } catch (\Exception $exception) {
            return [false, $exception->getMessage()];
        }
        return [true, '退出成功'];
    }

    public function read($id): mixed
    {
        $user = SystemUser::where(['id' => $id])
            ->with(['roles'])
            ->find();
        if (!$user) {
            return [];
        }
        return $user;
    }

    public function getList(?array $params = null, $field = ['*'])
    {
        $query = SystemUser::order(['id' => 'desc']);
        if ($username = Arr::get($params, 'username')) {
            $query->where(['username' => $username]);
        }
        if ($status = Arr::get($params, 'status')) {
            $query->where(['status' => $status]);
        }
        if ($phone = Arr::get($params, 'phone')) {
            $query->where(['phone' => $phone]);
        }
        if ($stockId = Arr::get($params, 'stock_id')) {
            $query->where(['stock_id' => $stockId]);
        }
        if ($fingerStatus = Arr::get($params, 'fingerprint_status')) {
            $option = $fingerStatus == 1 ? '<>' : '=';
            $query->where('fingerprint', $option, '');
        }
        $pagination = $query
            ->with('roles')
            ->field($field)
            ->paginate([
                'list_rows' => Arr::get($params, $this->listRowsName('system'), 15),
                'var_page' => 'page',
            ])->each(function (&$item) {
                unset($item['password'], $item['fingerprint']);
            });
        return pagination($pagination);
    }

    public function save($data)
    {
        if (!Arr::get($data, 'password')) {
            unset($data['password']);
        }
        if (SystemUser::where(['username' => Arr::get($data, 'username')])->find()) {
            return [false, '账户名称已经存在，不能重复添加'];
        }
        $roleIds = Arr::get($data, 'role_ids');
        try {
            $model = SystemUser::create($data)->roles()->sync(array_unique($roleIds));
        } catch (\Exception $exception) {
            return [false, $exception->getMessage()];
        }
        return [true, $model];
    }

    public function update($id, $data)
    {
        if (!$user = SystemUser::find($this->getUid())) {
            return [false, '用户信息不存在'];
        }
        return [true, SystemUser::update($data, ['id' => $user->id])];
    }

    public function updateWithRoles($id, $data)
    {
        $roleIds = Arr::get($data, 'role_ids');
        unset($data['role_ids'], $data['avatar_info']);
        try {
            $data['id'] = $id;
            $model = SystemUser::update($data, ['id' => $id])->roles()->sync(array_unique($roleIds));
        } catch (\Exception $exception) {
            return [false, $exception->getMessage()];
        }
        return [true, $model];
    }

    /**
     * 删除标注点
     * @param $id
     * @param $adminId
     * @return array
     */
    public function del($id, $adminId = 0)
    {
        $model = SystemUser::update([
            'deleted_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => $this->getUid($adminId),
        ], ['id' => $id]);
        return [true, $model];
    }

    /**
     * 绑定仓库
     * @param $uid
     * @param $stockId
     * @return array
     */
    public function bindStock($uid, $stockId): array
    {
        return [true, SystemUser::update(['stock_id' => $stockId], ['id' => $uid])];
    }


    public function getUserRouters()
    {
        $menuService = new MenuService();
        if ($this->isSuperAdmin()) {
            $data['roles'] = ['superAdmin'];
            $data['routers'] = $menuService->getSuperAdminRouters();
            $data['codes'] = ['*'];
            return $data;
        } else {
            /** @var SystemUser $user */
            $user = SystemUser::find($this->getUid());
            $roles = (new RoleService())->getMenuIdsByRoleIds($user->roles()->column('id'));
            $ids = $menuService->filterMenuIds($roles);
            $data['roles'] = $user->roles()->column('code');
            $data['routers'] = $menuService->getRoutersByIds($ids);
            $data['codes'] = $menuService->getMenuCode($ids);
            return $data;
        }
    }

    /**
     * 重置密码
     * @param $id
     * @return SystemUser
     */
    public function initPassword($id)
    {
        return SystemUser::update([
            'password' => '123456',
            'updated_by' => $this->getUid(),
            'updated_at' => date('Y-m-d H:i:s')
        ], ['id' => $id]);
    }

    /**
     * 修改密码，自身修改
     * @param $params
     * @return array
     */
    public function modifyPassword($params)
    {
        if (!$new = Arr::get($params, 'newPassword')) {
            return [false, '新密码不能为空'];
        }
        if (!$old = Arr::get($params, 'oldPassword')) {
            return [false, '旧密码不能为空'];
        }
        if (!$confirm = Arr::get($params, 'newPassword_confirmation')) {
            return [false, '确认密码不能为空'];
        }
        if ($new != $confirm) {
            return [false, '确认密码和新密码不一致'];
        }

        if (!$user = SystemUser::find($this->getUid())) {
            return [false, '用户信息不存在'];
        }

        if (!password_verify($old, $user->password)) {
            return [false, '旧密码不正确'];
        }
        SystemUser::update([
            'password' => $new,
            'updated_by' => $this->getUid(),
            'updated_at' => date('Y-m-d H:i:s')
        ], ['id' => $this->getUid()]);

        return [true, 'ok'];
    }

}